#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import time

from . import request, container

# 更新脚本
# 输入：
# index_states: 所有指数的状态，{'cs931187': {'updated': False, 'pe':0, 'pe_quantine':0, ...}}
# date: 需要更新的时间，精确到天，当天的数据可以做到实时变化，输入None可更新过去一年的数据
# 输出：
# index_states: 所有指数的状态，更新了哪个指数，就将其updated标志设为True

def update_index(index_number, index_states, date):
    index_data = request.request_index_data(index_number)
    if index_data == '':
        return

    key1 = 'var list_val = {'
    ss_pos1 = index_data.find(key1)
    if ss_pos1 != -1:
        ss1 = index_data[ss_pos1 + len(key1) - 2:]
        key2 = '};'
        ss_pos2 = ss1.find(key2)
        if ss_pos2 != -1:
            ss2 = ss1[:ss_pos2 + 1]
            dict_obj = eval(ss2)
            #val1: 加权PE，val2：等权PE
            pe_values = dict_obj['1']['list_val1']
            #print(pe_values)
            price_values = dict_obj['1']['list_price']
            date_values = dict_obj['1']['list_date']
            pe_30 = dict_obj['1']['list_val1_30']
            pe_70 = dict_obj['1']['list_val1_70']
            pe_p = dict_obj['1']['list_val1_p']
            if date is None:
                index_states[index_number] = {
                    'updated': True,
                    'values': []
                }
                values = index_states[index_number]['values']
                ipos = 0
                for dt in date_values:
                    values.append({
                        'date': dt,
                        'pe': pe_values[ipos],
                        'pe_quantile': pe_p[ipos],
                        'pe_oppotunity': pe_30[ipos],
                        'pe_danger': pe_70[ipos],
                        'market_value': price_values[ipos]
                    })
                    ipos = ipos + 1         
            else:
                ipos = container.find(date_values, date)
                if ipos != -1:
                    index_states[index_number] = {
                        'updated': True,
                        'pe': pe_values[ipos],
                        'pe_quantile': pe_p[ipos],
                        'pe_oppotunity': pe_30[ipos],
                        'pe_danger': pe_70[ipos],
                        'market_value': price_values[ipos]
                    }

if __name__ == '__main__':
    index_states = {}
    date = None
    update_index('sh000300', index_states, date)
    print(index_states)
    index_states = {}
    date = time.strftime("%Y-%m-%d")
    print(date)
    update_index('sh000300', index_states, date)
    print(index_states)
    
